{% extends "base.html" %}

{% block title %}我的课程 - IT课程数据分析系统{% endblock %}

{% block extra_css %}
<style>
    .courses-list {
        display: grid;
        gap: 1.5rem;
    }
    
    .course-item {
        background: white;
        border-radius: 8px;
        padding: 1.5rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        display: grid;
        grid-template-columns: 2fr 1fr 1fr auto;
        gap: 2rem;
        align-items: center;
        transition: all 0.3s;
    }
    
    .course-item:hover {
        box-shadow: 0 4px 16px rgba(0,0,0,0.15);
    }
    
    .course-info h3 {
        color: #2c3e50;
        margin-bottom: 0.5rem;
    }
    
    .course-code {
        color: #7f8c8d;
        font-size: 0.9rem;
    }
    
    .course-stat {
        text-align: center;
    }
    
    .course-stat .label {
        font-size: 0.85rem;
        color: #7f8c8d;
        margin-bottom: 0.5rem;
    }
    
    .course-stat .value {
        font-size: 1.75rem;
        font-weight: 700;
        color: #2c3e50;
    }
    
    .action-buttons {
        display: flex;
        gap: 0.5rem;
        flex-direction: column;
    }
    
    .action-buttons button {
        padding: 0.5rem 1rem;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 0.85rem;
        white-space: nowrap;
    }
    
    .btn-view {
        background: #3498db;
        color: white;
    }
    
    .btn-students {
        background: #2ecc71;
        color: white;
    }
    
    /* 模态框样式 */
    .modal {
        display: none; /* 默认隐藏 */
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 1000;
    }
    
    .modal.show {
        display: flex !important; /* 显示时使用flex布局 */
        justify-content: center;
        align-items: center;
    }
    
    .modal-content {
        background: white;
        border-radius: 8px;
        padding: 2rem;
        max-width: 600px;
        width: 90%;
        max-height: 90vh;
        overflow-y: auto;
        position: relative;
    }
    
    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
        padding-bottom: 1rem;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .modal-header h3 {
        margin: 0;
        color: #2c3e50;
    }
    
    .close {
        font-size: 1.5rem;
        color: #7f8c8d;
        cursor: pointer;
        line-height: 1;
        padding: 0;
        background: none;
        border: none;
    }
    
    .close:hover {
        color: #2c3e50;
    }
    
    .form-group {
        margin-bottom: 1rem;
    }
    
    .form-group label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 500;
        color: #2c3e50;
    }
    
    .form-group input,
    .form-group textarea {
        width: 100%;
        padding: 0.75rem;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        font-size: 1rem;
        font-family: inherit;
    }
    
    .form-group input:focus,
    .form-group textarea:focus {
        outline: none;
        border-color: #3498db;
    }
    
    .form-row {
        display: flex;
        gap: 1rem;
    }
    
    .form-actions {
        display: flex;
        gap: 1rem;
        justify-content: flex-end;
        margin-top: 1.5rem;
        padding-top: 1rem;
        border-top: 1px solid #e0e0e0;
    }
</style>
{% endblock %}

{% block content %}
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom:1.5rem;">
    <h2 style="margin: 0;">我的课程</h2>
    <button class="btn btn-primary" onclick="showCreateCourseModal()">
        <i class="fas fa-plus"></i> 创建新课程
    </button>
</div>

<div id="loading" class="loading">
    <div class="spinner"></div>
    <p>加载中...</p>
</div>

<div id="courses-content" style="display:none;">
    <div class="courses-list" id="courses-list"></div>
</div>

<!-- 创建课程模态框 -->
<div id="createCourseModal" class="modal">
    <div class="modal-content" style="max-width: 600px;">
        <div class="modal-header">
            <h3>创建新课程</h3>
            <span class="close" onclick="closeCreateCourseModal()">&times;</span>
        </div>
        <div class="modal-body">
            <form id="createCourseForm">
                <div class="form-group">
                    <label for="course_code">课程代码 *</label>
                    <input type="text" id="course_code" name="course_code" required 
                           placeholder="例如: CS101">
                </div>
                
                <div class="form-group">
                    <label for="course_name">课程名称 *</label>
                    <input type="text" id="course_name" name="course_name" required 
                           placeholder="例如: Python编程基础">
                </div>
                
                <div class="form-row">
                    <div class="form-group" style="flex: 1;">
                        <label for="credits">学分 *</label>
                        <input type="number" id="credits" name="credits" required 
                               min="0.5" max="10" step="0.5" value="3">
                    </div>
                    
                    <div class="form-group" style="flex: 1;">
                        <label for="max_students">最大人数</label>
                        <input type="number" id="max_students" name="max_students" 
                               min="1" max="500" value="100">
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="department">院系</label>
                    <input type="text" id="department" name="department" 
                           placeholder="例如: 计算机科学与技术学院">
                </div>
                
                <div class="form-row">
                    <div class="form-group" style="flex: 1;">
                        <label for="academic_year">学年</label>
                        <input type="text" id="academic_year" name="academic_year" 
                               placeholder="例如: 2023-2024">
                    </div>
                    <div class="form-group" style="flex: 1;">
                        <label for="semester_term">学期</label>
                        <select id="semester_term" name="semester_term">
                            <option value="">请选择</option>
                            <option value="1">第一学期</option>
                            <option value="2">第二学期</option>
                            <option value="3">第三学期</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group" style="flex: 1;">
                        <label for="classroom">教室</label>
                        <input type="text" id="classroom" name="classroom" 
                               placeholder="例如: A101">
                    </div>
                    
                    <div class="form-group" style="flex: 1;">
                        <label for="schedule">上课时间</label>
                        <input type="text" id="schedule" name="schedule" 
                               placeholder="例如: 周一 1-2节">
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="description">课程描述</label>
                    <textarea id="description" name="description" rows="3" 
                              placeholder="课程简介和教学目标..."></textarea>
                </div>
                
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeCreateCourseModal()">取消</button>
                    <button type="submit" class="btn btn-primary">创建课程</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let currentTeacherId = null;
    
    async function loadCourses() {
        try {
            const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
            currentTeacherId = userInfo.id;
            
            if (!currentTeacherId) {
                window.location.href = '/login';
                return;
            }
            
            const data = await apiRequest(`/teachers/${currentTeacherId}/courses`);
            
            if (data.success) {
                const courses = data.data;
                const container = document.getElementById('courses-list');
                
                if (courses.length === 0) {
                    container.innerHTML = '<div class="card"><p style="text-align:center;color:#7f8c8d;padding:2rem;">暂无授课课程</p></div>';
                    document.getElementById('loading').style.display = 'none';
                    document.getElementById('courses-content').style.display = 'block';
                    return;
                }
                
                // 为每门课程加载统计
                const coursesWithStats = await Promise.all(
                    courses.map(async (course) => {
                        try {
                            const statsData = await apiRequest(`/analytics/courses/${course.id}/statistics`);
                            return {
                                ...course,
                                stats: statsData.success ? statsData.data.statistics : null
                            };
                        } catch (error) {
                            return { ...course, stats: null };
                        }
                    })
                );
                
                container.innerHTML = coursesWithStats.map(course => `
                    <div class="course-item">
                        <div class="course-info">
                            <h3>${course.name}</h3>
                            <div class="course-code">${course.code} | ${course.credits} 学分 | ${formatSemester(course)}</div>
                            <p style="color:#7f8c8d;font-size:0.9rem;margin-top:0.5rem;">${course.description || '暂无描述'}</p>
                        </div>
                        
                        <div class="course-stat">
                            <div class="label">选课人数</div>
                            <div class="value">${course.stats ? course.stats.total_enrolled || 0 : 0}</div>
                        </div>
                        
                        <div class="course-stat">
                            <div class="label">平均分</div>
                            <div class="value" style="color:${course.stats && course.stats.average_score >= 75 ? '#27ae60' : '#7f8c8d'}">
                                ${course.stats && course.stats.average_score ? course.stats.average_score.toFixed(1) : '-'}
                            </div>
                        </div>
                        
                        <div class="action-buttons">
                            <button class="btn-view" onclick="window.location.href='/teacher/dashboard'">查看详情</button>
                            <button class="btn-students" onclick="viewStudents(${course.id})">学生列表</button>
                        </div>
                    </div>
                `).join('');
            }
            
            document.getElementById('loading').style.display = 'none';
            document.getElementById('courses-content').style.display = 'block';
            
        } catch (error) {
            showAlert('加载课程失败: ' + error.message, 'error');
            document.getElementById('loading').style.display = 'none';
        }
    }
    
    function viewStudents(courseId) {
        window.location.href = `/teacher/dashboard?course=${courseId}`;
    }
    
    window.addEventListener('DOMContentLoaded', () => {
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
        if (userInfo.role !== 'teacher') {
            showAlert('权限不足', 'error');
            setTimeout(() => window.location.href = '/', 2000);
            return;
        }
        
        loadCourses();
    });
    
    // 显示创建课程模态框
    function showCreateCourseModal() {
        const modal = document.getElementById('createCourseModal');
        modal.style.display = 'flex';
        modal.classList.add('show');
        document.getElementById('createCourseForm').reset();
    }
    
    // 关闭创建课程模态框
    function closeCreateCourseModal() {
        const modal = document.getElementById('createCourseModal');
        modal.style.display = 'none';
        modal.classList.remove('show');
    }
    
    // 处理创建课程表单提交
    document.getElementById('createCourseForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const formData = {
            course_code: document.getElementById('course_code').value.trim(),
            course_name: document.getElementById('course_name').value.trim(),
            credits: parseFloat(document.getElementById('credits').value),
            max_students: parseInt(document.getElementById('max_students').value) || 100,
            department: document.getElementById('department').value.trim(),
            academic_year: document.getElementById('academic_year').value.trim(),
            semester_term: document.getElementById('semester_term').value,
            classroom: document.getElementById('classroom').value.trim(),
            schedule: document.getElementById('schedule').value.trim(),
            description: document.getElementById('description').value.trim()
        };
        
        try {
            const data = await apiRequest('/teacher/courses', {
                method: 'POST',
                body: JSON.stringify(formData)
            });
            
            if (data.success) {
                showAlert('课程创建成功！', 'success');
                closeCreateCourseModal();
                loadCourses(); // 重新加载课程列表
            } else {
                showAlert(data.error || '创建失败', 'error');
            }
        } catch (error) {
            console.error('Error creating course:', error);
            showAlert('创建失败: ' + error.message, 'error');
        }
    });
    
    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('createCourseModal');
        if (event.target === modal) {
            closeCreateCourseModal();
        }
    };
</script>
{% endblock %}


